package com.tbvtc.agriculturalcreditchainserver2025.utils.Pest;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.tbvtc.agriculturalcreditchainserver2025.dto.Pest.cropPestReportDto;
import com.tbvtc.agriculturalcreditchainserver2025.entity.CameraCropMapping;
import com.tbvtc.agriculturalcreditchainserver2025.entity.Crop;
import com.tbvtc.agriculturalcreditchainserver2025.exception.FoodException;
import com.tbvtc.agriculturalcreditchainserver2025.mapper.CameraCropMappingMapper;
import com.tbvtc.agriculturalcreditchainserver2025.mapper.CropMapper;
import com.tbvtc.agriculturalcreditchainserver2025.pojo.pear.MainPestPear;
import com.tbvtc.agriculturalcreditchainserver2025.properties.ContractAdressProperties;
import com.tbvtc.agriculturalcreditchainserver2025.service.IpfsService;
import com.tbvtc.agriculturalcreditchainserver2025.utils.BlockBaseUtils;
import com.tbvtc.agriculturalcreditchainserver2025.utils.BlockchainUtils;
import com.tbvtc.agriculturalcreditchainserver2025.utils.ResultCodeEnum;
import com.tbvtc.agriculturalcreditchainserver2025.utils.UserType;
import com.tbvtc.agriculturalcreditchainserver2025.constant.RedisConstant;
import com.tbvtc.agriculturalcreditchainserver2025.vo.Pest.SendResultVo;
import lombok.extern.slf4j.Slf4j;
import org.fisco.bcos.sdk.transaction.model.dto.TransactionResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

@Slf4j
@Component
public class PestReportUtils {
    @Autowired
    private BlockchainUtils blockchainUtils;
    @Autowired
    private BlockBaseUtils blockBaseUtils;
    @Autowired
    private ContractAdressProperties contractAdressProperties;
    @Autowired
    @Qualifier("TredisTemplate")
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private PestHttpUtils pestHttpUtils;
    @Autowired
    private CameraCropMappingMapper cameraCropMapper;
    @Autowired
    private CropMapper cropMapper;

    @Resource
    private IpfsService pfsService;

    public void addPestReport(cropPestReportDto cropPestReport) {

        List<Object> list = List.of(cropPestReport.getCropName()
                , cropPestReport.getPestName()
                , cropPestReport.getPestSeverity()
                , cropPestReport.getPestPhotos()
                , cropPestReport.getTreatmentMethod()
        );
        try {
            TransactionResponse response = blockchainUtils.sendTransaction("FarmerManagement"
                    , "addCropPestReport"
                    , contractAdressProperties.getFarmerManagementAddress()
                    , list,
                    blockBaseUtils.getPemFilePath(UserType.FARMER));
        } catch (Exception e) {
            throw new FoodException(ResultCodeEnum.FAILED_TO_CHAIN);
        }
        String key = RedisConstant.CROP_PEST_PREFIX + cropPestReport.getCropName();
        redisTemplate.delete(key);
    }

    /**
     * 病虫害上链
     *
     * @param pestResult
     * @param hash
     * @return
     */
    public SendResultVo pestReportWinding(String pestResult, String hash) {
        JsonObject pestJson = JsonParser.parseString(pestResult).getAsJsonObject();//获取图像识别结果
        String aClass = pestJson.get(PestConstant.GetClassValue).getAsString();// 获取 "class" 字段的值 是否健康
//        aClass=PestConstant.GetPest;
        String probabilityStr = pestJson.get(PestConstant.GetProbabilityValue).getAsString(); // 获取 "probability" 字段的值 可信度
        double probability = Double.parseDouble(probabilityStr);
        cropPestReportDto cropPestReportDto = new cropPestReportDto();
        CameraCropMapping cameraCropMapping = cameraCropMapper.selectById(PestConstant.cameraId); //通过摄像头id获取到绑定的农作物id
        Crop cropDto = cropMapper.selectById(cameraCropMapping.getCropId()); //获取农作物实体
        cropPestReportDto.setCropName(cropDto.getName()); //农作物名字上链
        cropPestReportDto.setPestPhotos(hash); //图片上链
        if (aClass.equals(PestConstant.GetPest)) { //判断是否有病虫
            cropMapper.updatePest(cropDto.getId());
            log.info(String.valueOf(cropDto.getIsPest()));
            cropPestReportDto.setPestName(PestConstant.GetPestName); //状态上链
            if (probability < 0.25) { //若有病虫则根据置信度probability判断危害大小
                cropPestReportDto.setPestSeverity(PestConstant.GetLowPestSeverity);
            } else if (probability < 0.5) {
                cropPestReportDto.setPestSeverity(PestConstant.GetMidPestSeverity);
            } else if (probability < 0.75) {
                cropPestReportDto.setPestSeverity(PestConstant.GetHighPestSeverity);
            } else {
                cropPestReportDto.setPestSeverity(PestConstant.GetVeryHighPestSeverity);
            }
            String crop = cropPestReportDto.getCropName().substring(0, 4);
            String prompt = "农作物" + crop + "现在有了病虫害，主要表示在叶子萎靡不振，严重程度为" + probability + "这个表示0到1之间数字越大危害越大，请你给出解决方案";
//            String methodByAi = pestHttpUtils.getTreatmentMethodByAi(prompt);
            //            cropPestReportDto.setTreatmentMethod(methodByAi);//智能体建议上链
            cropPestReportDto.setTreatmentMethod("methodByAi");
            addPestReport(cropPestReportDto);

        } else { //若没有病虫害，返回健康的信息
            cropPestReportDto.setPestName(PestConstant.GetHealthName);
            cropPestReportDto.setPestSeverity(PestConstant.GetNo);
            cropPestReportDto.setTreatmentMethod(PestConstant.GetNo);
            addPestReport(cropPestReportDto);
        }
        return new SendResultVo(cropPestReportDto.getCropName(), aClass, probabilityStr, hash); //返回给客户端的数据
    }

    public void addPearPestReport(MainPestPear mainPestPear, String hash) {

        cropPestReportDto cropPestReportDto = new cropPestReportDto();
        CameraCropMapping cameraCropMapping = cameraCropMapper.selectById(PestConstant.cameraId); //通过摄像头id获取到绑定的农作物id
        Crop cropDto = cropMapper.selectById(cameraCropMapping.getCropId()); //获取农作物实体
        cropPestReportDto.setCropName(cropDto.getName()); //农作物名字上链
        if (!mainPestPear.getIs_healthy()) {
            cropMapper.updatePest(cropDto.getId());
            cropPestReportDto.setPestName(mainPestPear.getMain_prediction().getClass_name_zh());//病虫害名称
            cropPestReportDto.setPestPhotos(hash);
            cropPestReportDto.setPestSeverity(mainPestPear.getMain_prediction().getDisease_info().getSeverity());
            cropPestReportDto.setTreatmentMethod(mainPestPear.getMain_prediction().getDisease_info().getPrevention() +
                    mainPestPear.getMain_prediction().getDisease_info().getTreatment()
            );
            addPestReport(cropPestReportDto);
        } else {
            cropPestReportDto.setPestName(mainPestPear.getHealth_status());//健康
            cropPestReportDto.setPestPhotos(hash);
            cropPestReportDto.setPestSeverity("无");
            cropPestReportDto.setTreatmentMethod("无");
            addPestReport(cropPestReportDto);
        }


    }
}
